package com.tywj.panda.user

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.lifecycle.Observer
import com.afollestad.materialdialogs.MaterialDialog
import com.alibaba.android.arouter.facade.annotation.Route
import com.autocareai.lib.extension.visible
import com.blankj.utilcode.util.NetworkUtils
import com.tywj.panda.customer.common.cache.CommonCache
import com.tywj.panda.customer.common.entity.UserEntity
import com.tywj.panda.customer.common.event.UserEvent
import com.tywj.panda.customer.common.http.PDObjectCallback
import com.tywj.panda.customer.common.provider.ILaunchService
import com.tywj.panda.customer.common.provider.INavigationService
import com.tywj.panda.customer.common.provider.IUserCenterService
import com.tywj.panda.customer.common.tool.AuthorityTool
import com.tywj.panda.customer.common.tool.LogoutTool
import com.tywj.panda.customer.common.view.base.MyBaseFragment
import com.tywj.panda.customer.common.view.dialog.showByCZConfig
import com.tywj.panda.user.route.UserRoute
import com.tywj.lib.core.common.extension.loadRound
import com.tywj.lib.core.common.extension.onClick
import com.tywj.lib.core.common.util.BarUtil
import com.tywj.lib.core.common.util.PhoneUtil
import com.tywj.lib.core.common.util.ResourcesUtil
import com.tywj.lib.route.RouteUtil
import com.tywj.panda.customer.usercenter.cache.UserCenterCache
import com.tywj.panda.customer.usercenter.settings.TipsDialog
import kotlinx.android.synthetic.main.user_fragment_user.*

@Route(path = UserRoute.USER)
class UserFragment : MyBaseFragment() {

    override fun getLayoutID(): Int = R.layout.user_fragment_user

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        checkLoginState()
    }

    override fun initListener() {
        super.initListener()

        ivHeader.onClick {

            LogoutTool.checkLoginStatus(requireActivity()) {
                //到用户中心
                RouteUtil.getServiceProvider(IUserCenterService::class.java)?.toUserCenterInfo()?.navigation(this)
            }
        }

        ivCenter.onClick {
            LogoutTool.checkLoginStatus(requireActivity()) {
                //到用户中心
                RouteUtil.getServiceProvider(IUserCenterService::class.java)?.toUserCenterInfo()?.navigation(this)
            }
        }

        flFeedBack.onClick {
            LogoutTool.checkLoginStatus(requireActivity()) {
                //到用户反馈
                RouteUtil.getServiceProvider(IUserCenterService::class.java)?.toUserFeedBack()?.navigation(this)

            }
        }


        UserEvent.loadUserDataSuccessEvent.observe(this, Observer {
            // 用户信息发生变化，重新请求用户信息
            loadUserInfo(it)
        })


        //登录状态判断
        tvUserName.onClick {
            if (LogoutTool.isLogin) {
                return@onClick
            }
            //如何判断有4G、3G/2G 和wifi共存的网络类型，交给一键登录sdk去校验
            if (NetworkUtils.isConnected()) {
                toLoginAuthActivity()
            } else {
                shortToast(R.string.common_please_check_network_state)
            }
        }
        tvMineOrder.onClick {

            LogoutTool.checkLoginStatus(requireActivity()) {
                UserRoute.toOrderRecord().navigation(this)
            }

        }

        //申请路线
        tvRoute.onClick {

            shortToast("开发中，敬请期待")
//            LogoutTool.checkLoginStatus(requireActivity()) {
//                RouteUtil.getServiceProvider(INavigationService::class.java)?.toApplyCourse()?.navigation(this)
//            }
        }

        flServiceCenter.onClick {

            TipsDialog.Builder(this)
                .setTipDetails(ResourcesUtil.getString(R.string.common_prompt_call_customer_service_message))
                .setConfirmListener {
                    PhoneUtil.call(requireContext(), ResourcesUtil.getString(R.string.common_customer_service_phone))
                }
                .show()
        }

        //设置
        flUserSettings.onClick {
            RouteUtil.getServiceProvider(IUserCenterService::class.java)?.toSetting()?.navigation(this)

        }
    }

    override fun onVisibleEveryTime() {
        super.onVisibleEveryTime()
        activity?.let {

            BarUtil.setStatusBarColor(it, ResourcesUtil.getColor(R.color.common_yellow_FE))
            BarUtil.setStatusBarLightMode(it.window, true)
        }
    }

    override fun onVisibleFirst() {
        super.onVisibleFirst()

        loadUserInfo(AuthorityTool.uid)
    }

    private fun toLogin() {
        toLoginAuthActivity()
    }

    //一键登录
    private fun toLoginAuthActivity() {
        RouteUtil.getServiceProvider(ILaunchService::class.java)
            ?.toAuthLogin()
            ?.navigation(this)
    }

    //手机号登录
    private fun toLoginByPhone() {
        RouteUtil.getServiceProvider(ILaunchService::class.java)
            ?.toLoginByPhone()
            ?.navigation(this)
    }

    //更新用户信息
    @SuppressLint("SetTextI18n")
    private fun loadUserInfo(uid: String) {
        showLoadingDialog()

        RouteUtil.getServiceProvider(IUserCenterService::class.java)?.getUserDetails(uid)?.attachToLifecycle(this)
            ?.execute(object : PDObjectCallback<UserEntity>(UserEntity::class.java) {
                override fun success(data: UserEntity) {

                    tvUserName.text = if (data.nickName.isNullOrEmpty()) {
                        ResourcesUtil.getString(R.string.user_center_set_nickname)
                    } else {
                        data.nickName
                    }
                    data.avatar?.let {
                        ivHeader.loadRound(it, R.drawable.common_portrait_default)
                    }
                    tvUserId.text = "ID:${data.uid}"
                    visible(tvUserId)

                    UserCenterCache.userInfo = data
                }

                override fun error(code: Int, message: String) {
                    super.error(code, message)
                    shortToast(message)
                }

                override fun onComplete() {
                    super.onComplete()
                    dismissLoadingDialog()
                }
            })
    }

    @SuppressLint("SetTextI18n")
    private fun checkLoginState() {
        if (LogoutTool.isLogin) {
            UserCenterCache.userInfo?.let {
                tvUserName.text = ResourcesUtil.getString(R.string.user_had_logined)
                tvUserId.text = "ID:" + CommonCache.uid

                it.avatar.let { avatar ->
                    ivHeader.loadRound(avatar, R.drawable.common_portrait_default)
                }

                visible(tvUserId)
            }
        } else {
            tvUserName.text = ResourcesUtil.getString(R.string.user_please_login)
            tvUserId.text = "更多精彩，请登录后使用"
        }
    }

    private fun showPromptCallCustomerServiceDialog() {
        MaterialDialog(requireContext())
            .title(R.string.common_prompt_title)
            .message(R.string.common_prompt_call_customer_service_message)
            .negativeButton(R.string.common_negative)
            .positiveButton(R.string.common_positive) {
                PhoneUtil.call(requireContext(), ResourcesUtil.getString(R.string.common_customer_service_phone))
            }
            .showByCZConfig()
    }
}